package AdminDocker

import (
	"autoDeploy/models"
	"autoDeploy/utils/DingTalk"
	"fmt"
	"gorm.io/gorm"
)

// GetTeams 加载管理员团队页面资源
func GetTeams() ([]TeamMessage, error) {
	var TeamMsg []TeamMessage
	teams, err := models.Team{}.GetAllTeams(db)
	if err != nil {
		return nil, fmt.Errorf("service层 获取所有团队失败 GetTeams: %s", err)
	}
	length := len(teams)
	for i := 0; i < length; i++ {
		team := teams[i]
		captain, err := models.GetUserByID(db, team.CaptainUserID)
		if err != nil {
			return nil, fmt.Errorf("service层 获取队长失败 GetUserByID: %s", err)
		}
		proId, err := models.GetProjectIDByTeamID(db, team.ID)
		if err != nil {
			return nil, fmt.Errorf("service层 获取项目id失败 GetProjectIDByTeamID: %s", err)
		}
		project, err := models.GetProjectByID(db, proId)
		if err != nil {
			return nil, fmt.Errorf("service层 获取项目失败 GetProjectByID: %s", err)
		}
		num, _, err := models.GetTeamMemberIDs(db, team.ID)
		if err != nil {
			return nil, fmt.Errorf("service层 获取团队成员个数 GetTeamMemberIDs: %s", err)
		}
		TeamMsg = append(TeamMsg, TeamMessage{
			TeamID:          team.ID,
			TeamName:        team.Name,
			TeamCaptainName: captain.Username,
			TeamProjectID:   project.ID,
			TeamProjectName: project.Name,
			TeamMemberNum:   uint64(num),
			TeamAddress:     team.Address,
		})
	}
	return TeamMsg, nil
}

// DeleteTeam 管理员解散团队
func DeleteTeam(teamID uint64, projectID uint64, address string) error {
	// 开启事务
	err := db.Transaction(func(tx *gorm.DB) error {
		//删除用户团队关联表的数据
		err := models.UserTeam{}.DeleteUserTeamsByTeamID(db, teamID)
		if err != nil {
			return fmt.Errorf("删除用户团队关联表的数据失败：%s", err)
		}
		//删除用户团队角色表
		err = models.UserProRole{}.DeleteUserProRoleByTeamID(db, teamID)
		if err != nil {
			return fmt.Errorf("删除用户团队角色表 失败：%s", err)
		}
		//删除团队记录
		err = models.Team{}.DeleteTeamByID(db, teamID)
		if err != nil {
			return fmt.Errorf("删除团队记录 失败：%s", err)
		}
		//删除团队项目
		err = models.TeamProject{}.DeleteTeamProjectByTeamID(db, teamID)
		if err != nil {
			return fmt.Errorf("删除团队项目 失败：%s", err)
		}
		//删除项目记录
		err = models.Project{}.DeleteProjectByID(db, projectID)
		if err != nil {
			return fmt.Errorf("删除项目记录 失败：%s", err)
		}
		//删除项目推送信息
		err = models.ProPusherMsg{}.DeleteProPusherMsgByProjectID(db, projectID)
		if err != nil {
			return fmt.Errorf("删除项目推送信息 失败：%s", err)
		}
		//删除项目版本号记录
		err = models.ProjectTag{}.DeleteProjectTagsByProjectID(db, projectID)
		if err != nil {
			return fmt.Errorf("删除项目版本号记录 失败：%s", err)
		}
		//删除项目Git记录
		err = models.GitProDetails{}.DeleteGitProDetailsByProjectID(db, projectID)
		if err != nil {
			return fmt.Errorf("删除项目Git记录 失败：%s", err)
		}
		return nil
	})
	if err != nil {
		return fmt.Errorf("service层 DeleteTeam管理员解散团队 失败%s", err)
	}
	//发送消息
	err = DingTalk.SendMessageToDingTalkTeamDisbanded(address)
	if err != nil {
		return fmt.Errorf("service层 发送钉钉消息 失败%s", err)
	}

	return nil
}
